<?php

/*
function TransferData()
{
	//导数据的程序

	$mysqliA = new mysqli("localhost", "lazier", "4685489", "acm");
	if (mysqli_connect_errno()) {
    	printf("Mysql Connect failed: %s\n", mysqli_connect_error());
    	exit(-1);
	}

	$mysqliB = new mysqli("localhost", "lazier", "4685489", "icpcmgr");
	if (mysqli_connect_errno()) {
    	printf("Mysql Connect failed: %s\n", mysqli_connect_error());
   		exit(-1);
	}

	$mysqliA->query("set names latin1");
	$mysqliB->query("set names utf8");

	$resultA = $mysqliA->query("select * from users", MYSQLI_USE_RESULT);
	while($row = $resultA->fetch_array(MYSQLI_ASSOC))
	{
		$sql = "insert into userlist(username, password, nickname, sex, school, email, imagesrc, intra, ip, rgtime, permission) values(";
		$sql .= "'".$row["username"]."',";
		$sql .= "'".$row["password"]."',";
		$sql .= "'".$row["nickname"]."',";
		$sql .= "'".$row["sex"]."',";
		$sql .= "'".$row["school"]."',";
		$sql .= "'".$row["email"]."',";
		$sql .= "'".$row["image"]."',";
		$sql .= "'".$row["intra"]."',";
		$sql .= "'".$row["ip"]."',";
		$sql .= "'".$row["rgtime"]."',";
		$sql .= "'".$row["permission"]."'";
		$sql .= ")";
		
		//echo $sql."<br />";
		$mysqliB->query($sql, MYSQLI_USE_RESULT);
	}

	$resultA->close();
	$mysqliA->close();
	$mysqliB->close();
}

*/

// 获得mysqli对象， 但是记住在使用完后调用->close()函数释放连接

function GetMysqliInstance()
{
	$mysqli = new mysqli("localhost", "lazier", "4685489", "icpcmgr");
	if (mysqli_connect_errno()) {
    	printf("Mysql Connect failed: %s\n", mysqli_connect_error());
    	exit(-1);
	}
	$mysqli->query("set names utf8");
	return $mysqli;
}

// 实例代码

// {
// 	$mysqli = GetMysqliInstance();

// 	$result = $mysqli->query("select * from users");
// 	$row = $result->fetch_array(MYSQLI_BOTH);
// 	printf ("%s (%s)\n", $row[0], $row["username"]);  

// 	// free result set 
// 	$result->close();

// 	// close connection
// 	$mysqli->close();
// }

function GetRequestIP(){ 
	if (getenv("HTTP_CLIENT_IP") && strcasecmp(getenv("HTTP_CLIENT_IP"), "unknown")) 
		$ip = getenv("HTTP_CLIENT_IP"); 
	else if (getenv("HTTP_X_FORWARDED_FOR") && strcasecmp(getenv("HTTP_X_FORWARDED_FOR"), "unknown")) 
		$ip = getenv("HTTP_X_FORWARDED_FOR"); 
	else if (getenv("REMOTE_ADDR") && strcasecmp(getenv("REMOTE_ADDR"), "unknown")) 
		$ip = getenv("REMOTE_ADDR"); 
	else if (isset($_SERVER['REMOTE_ADDR']) && $_SERVER['REMOTE_ADDR'] && strcasecmp($_SERVER['REMOTE_ADDR'], "unknown")) 
		$ip = $_SERVER['REMOTE_ADDR']; 
	else 
		$ip = "unknown"; 
	return($ip); 
}

function GetSysTime($timestamp = -1)
{
	if ($timestamp == -1)
		$timestamp = time();
	return date("Y-m-d H:i:s", $timestamp);
}

function IsValidEmail($email)
{
	if (strlen($email) > 320) // 邮箱的地址的最大长度是320
		return false;
	$pattern = "/^([0-9A-Za-z\\-_\\.]+)@([0-9a-z]+\\.[a-z]{2,3}(\\.[a-z]{2})?)$/i";
	if (preg_match($pattern, $email))
		return true;
	else
		return false;
}

function ToNum($ch)
{
	if(ord($ch) <= 57 && ord($ch) >= 48)
		return ord($ch) - 48;
	else if(ord($ch) >= 97)
		return ord($ch) - 87;
}

function Decode($str)
{
	$res = "";
	$len = strlen($str);
	for($i = 0; $i < $len; $i += 2)
	{
		$res .= chr(ToNum($str[$i]) * 16 + ToNum($str[$i + 1]));
	}

	$res=base64_decode($res);

	return $res;
}

function Encode($str)
{
	$res = "";
	$map = "0123456789abcdef";
	$str = base64_encode($str);
	$len = strlen($str);
	for($i=0; $i < $len; ++$i)
	{
		$ascii = ord($str[$i]);
		$h = $ascii / 16;
		$d = $ascii % 16;
		$res .= $map[$h].$map[$d];
	}
	return $res;
}

function CheckAdminAndInitHeader()
{
	ob_start();
	session_start();
	if (!isset($_SESSION["admin"]))
	{
		ob_end_clean();
		ob_get_clean();
		header("HTTP/1.0 403 Forbidden");
		header("Content-Type: text/plain; charset=UTF-8");
		exit(0);
	}
	else  header("Content-Type: text/html; charset=UTF-8");
}

function GetFileContent($filepath)
{
	if (file_exists($filepath))
	{
		$fp = fopen($filepath, "r");
		$content = fread($fp, filesize($filepath));
		fclose($fp);
		return $content;
	}
	return "";
}

function SetFileContent($filepath, $content)
{
	$fp = fopen($filepath, "w");
	$ret = fwrite($fp, $content);
	fclose($fp);
	return $ret;
}


function GetFileNameById($id)
{
	$filename = "icpc.htm";
	switch($id)
	{
		case 1: $filename  = "team.htm"; break;
		case 2: $filename  = "icpc.htm"; break;
		case 3: $filename  = "teacher.htm"; break;
		case 4: $filename  = "book.htm"; break;
	}
	return $filename;
}

function JudgeUpLoadImageFile(&$file)
{
	if($file["type"] == "image/gif"
		|| $file["type"] == "image/jpe"
		|| $file["type"] == "image/jpeg"
		|| $file["type"] == "image/pjpeg"
		|| $file["type"] == "image/png"
		|| $file["type"] == "image/bmp")
	{
		if($file["size"] <= 1024 * 1024 * 5)
			return true;
	}
	echo $file["type"];
	return false;
}

function GetFilePathExtension($str)
{
	$extArr = array('.jpe','.jpg','.jpeg','.gif','.png','.bmp');
	$extension = "";
	if ($pos = strrpos($str, "."))
		$extension = substr($str, $pos);

	$ret = false;
	foreach ($extArr as $value){
	 	if ($extension == $value)
	 	{
	 		$ret = true;
			break;
		}
	 }

	if (!$ret)
		$extension = "";

	return $extension;
}

function CheckStrInNumAndChar($str)
{
	$ret = true;
	$len = strlen($str);
	for ($i = 0; $i < $len; ++$i)
	{
		if (($str[$i] >= '0' && $str[$i] <= '9') 
			|| ($str[$i] >= 'a' && $str[$i] <= 'z')
			|| ($str[$i] >= 'A' && $str[$i] <= 'Z'));
		else 
		{
			$ret = false;
			break;
		}
	}
	return $ret;	
}

function UploadImage($file, $path)
{
   	if($file["error"]==1)
		die("<span style=\"color:red\">图片上传失败<br />文件大小超过服务器上传限制</span>");
   	else if($file["error"]==2)
       	 	die("<span style=\"color:red\">图片上传失败<br />文件大小超过浏览器上传限制</span>");
  	else if($file["error"]==3)
		die("<span style=\"color:red\">图片上传失败<br />文件不完整，只被部分上传</span>");
        else if($file["error"]==4)
        	die("<span style=\"color:red\">图片上传失败<br />服务器无法找到上传文件</span>");
   	return move_uploaded_file($file["tmp_name"], $path) or die("服务器图片文件储存失败");
}

function imagecreatefrombmp($p_sFile){ 
    $file = fopen($p_sFile,"rb"); 
    $read = fread($file,10); 
    while(!feof($file)&&($read<>"")) 
    $read .= fread($file,1024); 
    $temp = unpack("H*",$read); 
    $hex =  $temp[1]; 
    $header = substr($hex,0,108); 
    if (substr($header,0,4)=="424d"){ 
        $header_parts = str_split($header,2); 
        $width = hexdec($header_parts[19].$header_parts[18]); 
        $height = hexdec($header_parts[23].$header_parts[22]); 
        unset($header_parts); 
    }

    $x = 0; 
    $y = 1; 
    $image = imagecreatetruecolor($width,$height); 
    $body = substr($hex,108); 
    $body_size = (strlen($body)/2); 
    $header_size = ($width*$height); 
    $usePadding = ($body_size>($header_size*3)+4); 
    for ($i=0;$i<$body_size;$i+=3){ 
        if ($x>=$width){ 
           	if ($usePadding) 
                	$i += $width%4; 
            $x = 0; 
           	$y++; 
            if ($y>$height) 
                break; 
        } 
        $i_pos    =    $i * 2; 
        $r        =    hexdec($body[$i_pos+4].$body[$i_pos+5]); 
        $g        =    hexdec($body[$i_pos+2].$body[$i_pos+3]); 
        $b        =    hexdec($body[$i_pos].$body[$i_pos+1]); 
        $color    =    imagecolorallocate($image,$r,$g,$b); 
        imagesetpixel($image,$x,$height-$y,$color); 
        $x++; 
    } 
    unset($body); 
    return $image; 
} 

function GetServerImgName($imgFileName)
{
	return md5(time().$imagFileName).GetFilePathExtension($imgFileName);
}

function GetFormalImgPath($imgFileName)
{
	return "./images/pic/".GetServerImgName($imgFileName);
}

function GetMiniImgPath($path)
{
	return "./images/pic_min/".GetServerImgName($imgFileName);
}

function CreateMiniImage($path,$miniPath)
{
	$width =  $GLOBALS["img_acmer_width"];
	$height = $GLOBALS["img_acmer_height"];

	$imgSize = GetImageSize($path);
    $imgType = $imgSize[2];
  
    //@ 使函数不向页面输出错误信息
    switch ($imgType)
    {
        case 1:
            $srcImg = @ImageCreateFromGIF($path);
            break;
        case 2:
            $srcImg = @ImageCreateFromJpeg($path);
            break;
        case 3:
            $srcImg = @ImageCreateFromPNG($path);
            break;
        case 6:
        	$srcImg = imagecreatefrombmp($path);
        	break;
    }

    $srcW = ImageSX($srcImg);
    $srcH = ImageSY($srcImg);

    if ($srcW > $width || $srcH > $height)
    {
		if(function_exists("ImageCreateTrueColor"))
	        $targetImg=ImageCreateTrueColor($width,$height);
	    else
	        $targetImg=ImageCreate($width,$height);

	    $white = ImageColorAllocate($targetImg, 255,255,255);
	    ImageFilledRectangle($targetImg,0,0,$width,$height,$white);

		if(function_exists("ImageCopyResampled"))
		{
	        ImageCopyResampled($targetImg,$srcImg,0,0,0,0,$width,$height,$srcW,$srcH);
		}
	    else
	    {
	        ImageCopyResized($targetImg,$srcImg,0,0,0,0,$width,$height,$srcW,$srcH);
	    }

	    switch ($imgType) {
	        case 1:
	            ImageGIF($targetImg,$miniPath);
	        	break;
	        case 2:
	            ImageJpeg($targetImg,$miniPath);
	            break;
	        case 3:
	            ImagePNG($targetImg,$miniPath);
	            break;
	    }
	    ImageDestroy($srcImg);
    	ImageDestroy($targetImg);    
	}
	else 
	{
		copy($path,$miniPath);
		ImageDestroy($srcImg);
	}

	return $miniPath;
}

function ClientRedirect($url, $tip = "")
{
	echo "<script type='text/javascript'>";
	if ($tip != "")
		echo "alert('$tip');";
	echo "window.location=\"$url\";</script>";
}

function ClientAlert($tip)
{
	echo "<script type='text/javascript'>";
	echo "alert('$tip');";
	echo "</script>";
}

function AddDateByMonth($Date, $Cnt)
{
	$year = substr($Date, 0, 4);
	$month = substr($Date, 5, 2);
	$year += intval($Cnt / 12);
	$month += intval($Cnt % 12);
	if (intval($month) > 12)
	{
		$year += 1;
		$month -= 12;
	}
	if (intval($month) < 0)
	{
		$year -= 1;
		$month += 12;
	}
	return sprintf("%04d-%02d",$year,$month); 
}

function StrCutUTF8($str, $len) 
{
    $mbchars = array();
    for( $i=0, $I=strlen($str), $L=0; $L<$len && $i<$I;) {
        $char = substr($str, $i, 1);
        switch ( true ) {
            default :
                $chars[] = substr($str, $i, 1); $L++; $i++; break;
            case ( ord($char) >= 252 ) :
                $chars[] = substr($str, $i, 6); $L++; $i += 6; break;
            case ( ord($char) >= 248 ) :
                $chars[] = substr($str, $i, 5); $L++; $i += 5; break;
            case ( ord($char) >= 240 ) :
                $chars[] = substr($str, $i, 4); $L++; $i += 4; break;
            case ( ord($char) >= 224 ) :
                $chars[] = substr($str, $i, 3); $L++; $i += 3; break;
            case ( ord($char) >= 192 ) :
                 $chars[] = substr($str, $i, 2); $L++; $i += 2; break;
        }
    }
    return implode('', $chars);
}

function IsDigitInStr($str)
{
	$len = strlen($str);
	for ($i = 0; $i < $len; ++$i)
	{
		if (ord($str[$i]) < 48 || ord($str[$i]) > 57)
			return false;
	}
	return true;
}

?>